﻿#include "apiprovider.h"
#include <QJsonDocument>
#include <QJsonParseError>
#include <QFile>
#include <QFileInfo>
#include <QStandardPaths>
#include <QGuiApplication>
#include <QUrl>
#include <QUuid>
#include <qwindowsmanager.h>

ApiProvider::ApiProvider(QObject *parent) : QObject(parent)
{  
    QString exeFilePath= QGuiApplication::applicationFilePath();  //在开发模式下，直接使用QApplication::applicationDirPath()可能不准确，因此需要手动计算
    QFileInfo exeInfo(exeFilePath);

    m_appName=exeInfo.fileName();
    m_appPath=exeInfo.absolutePath();
    m_appBaseName=exeInfo.baseName();

    m_configPath=m_appPath+"/config";
    QDir d(m_configPath);
    if(!d.exists()){
        d.mkpath(m_configPath);
    }

    m_qmlEngine=new QQmlEngine(this);
    m_qmlEngine->addImportPath(QStringLiteral("qrc:/"));
    m_qmlEngine->rootContext()->setContextProperty("ApiProvider",this);
    connect(m_qmlEngine,&QQmlEngine::quit,[=](){
        this->closeAllWindow();
        qApp->quit();
    });

    m_qmlMainFilePath=QStringLiteral("qrc:/ui/main.qml");
    m_qmlComponent=new QQmlComponent(m_qmlEngine,QUrl(m_qmlMainFilePath));
}

void ApiProvider::loadWindow()
{
    QVector<QString> ids=getConfigIds();
    if(ids.isEmpty()){
        addWindow();
    }else{
        for (int i = 0; i < ids.size(); i++) {
           addWindow(ids[i]);
        }
    }
}

void ApiProvider::addWindow()
{
    addWindow(QUuid::createUuid().toString());
}

void ApiProvider::addWindow(const QString& configId)
{
    QString configPath=m_configPath+"/"+configId;
    QDir d(configPath);
    if(!d.exists()){
        d.mkpath(configPath);
    }

    QQmlContext* context=new QQmlContext(m_qmlEngine,this);
    context->setContextProperty("configId",configId);

    QObject *object = m_qmlComponent->create(context);
    QQuickWindow *window = qobject_cast<QQuickWindow *>(object);
    window->setProperty("configId",configId);
    window->show();
    m_qmlWindows.push_back(window);
}

void ApiProvider::removeWindow(const QString &configId)
{
    QString configPath=m_configPath+"/"+configId;
    removeDirectory(configPath);

    for(int i=0;i<m_qmlWindows.size();i++){
        if(m_qmlWindows[i]->property("configId").toString() == configId){
            QQuickWindow* w= m_qmlWindows[i];
            w->close();
            w->deleteLater();
            m_qmlWindows.remove(i);
            break;
        }
    }

    if(m_qmlWindows.isEmpty()){
        addWindow();
    }
}

void ApiProvider::closeAllWindow()
{
    for(int i=0;i<m_qmlWindows.size();i++){
         m_qmlWindows[i]->close();
    }
}

QVector<QString> ApiProvider::getConfigIds()
{
    QVector<QString> ids;

    QDir dir(m_configPath);
    QFileInfoList fileInfoList = dir.entryInfoList();
    if(!fileInfoList.empty()){
        int i=0;
          do
          {
              QFileInfo fileInfo = fileInfoList.at(i);
              if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
              {
                  ++i;
                  continue;
              }

              if(fileInfo.isDir()){
                 ids.push_back(fileInfo.fileName());
              }
              ++i;
          }while(i<fileInfoList.size());
    }

    return ids;
}

QJsonArray ApiProvider::readList(const QString& id,const QString& name)
{    
    QFile file(m_configPath + "/"+ id + "/" + name+ ".json");
    if(file.exists()){
        if(file.open(QFile::ReadOnly)){
            QByteArray bytes  = file.readAll();
            QJsonParseError err;
            QJsonDocument doc = QJsonDocument::fromJson(bytes,&err);
            if(err.error == QJsonParseError::NoError){
                if(doc.isArray()){
                    return doc.array();
                }
            }

            file.close();
        }
    }

    return QJsonArray();
}

void ApiProvider::saveList(const QString& id,const QString& name, const QJsonArray& items)
{
    QDir d(m_configPath + "/"+ id);
    if(!d.exists()){
        d.mkpath(d.absolutePath());
    }

    QFile file(m_configPath + "/"+ id + "/"+ name + ".json");
    if(file.open(QFile::WriteOnly | QFile::Text)){
        QJsonDocument doc(items) ;
        file.write(doc.toJson());
        file.flush();
        file.close();
    }
}

QJsonObject ApiProvider::readAppConfig(const QString& id)
{
    QFile file(m_configPath + "/"+id+"/app.json");
    if(file.exists()){
        if(file.open(QFile::ReadOnly)){
            QByteArray bytes  = file.readAll();
            QJsonParseError err;
            QJsonDocument doc = QJsonDocument::fromJson(bytes,&err);
            if(err.error == QJsonParseError::NoError){
                if(doc.isObject()){
                    return doc.object();
                }
            }

            file.close();
        }
    }

    return QJsonObject();
}

void ApiProvider::saveAppConfig(const QString& id,const QJsonObject& obj)
{
    QDir d(m_configPath + "/"+ id);
    if(!d.exists()){
        d.mkpath(d.absolutePath());
    }

    QFile file(m_configPath + "/"+id+"/app.json");
    if(file.open(QFile::WriteOnly | QFile::Text)){
        QJsonDocument doc(obj) ;
        file.write(doc.toJson());
        file.flush();
        file.close();
    }

    bool autoStart = obj.value("autoStart").toBool(false);
    m_appPath.replace("/","\\");
    QWindowsManager::setAutoStartEnabled(m_appBaseName,m_appPath+"\\"+m_appName,autoStart);
}

bool ApiProvider::removeDirectory(const QString &dirPath) {
    QDir dir(dirPath);

    if (!dir.exists()) {
        return false;
    }

    // 获取目录中的所有条目，包括隐藏文件
    foreach (QFileInfo fileInfo, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries, QDir::DirsFirst)) {
        if (fileInfo.isDir()) {
            // 递归删除子目录
            if (!removeDirectory(fileInfo.absoluteFilePath())) {
                return false;
            }
        } else {
            // 删除文件
            if (!QFile::remove(fileInfo.absoluteFilePath())) {
                return false;
            }
        }
    }

    // 删除目录本身
    if (!dir.rmdir(dirPath)) {
        return false;
    }

    return true;
}
